package com.ziyunying.weather.repository

import android.content.Context
import com.ziyunying.weather.api.AMapLocationApi
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class LocationRepository @Inject constructor(
    @ApplicationContext private val context: Context,
    private val locationApi: AMapLocationApi
) {
    private val _locationData = MutableStateFlow<String?>(null)
    val locationData: StateFlow<String?> = _locationData

    private val _locationError = MutableStateFlow<String?>(null)
    val locationError: StateFlow<String?> = _locationError

    // 默认位置（北京）
    private val defaultLocation = "101010100"
    private val defaultCity = "北京"

    private val _currentCity = MutableStateFlow(defaultCity)
    val currentCity: StateFlow<String> = _currentCity

    fun getUserLocation(onComplete: (String) -> Unit) {
        locationApi.getLocation(
            onSuccess = { location ->
                // 定位成功，使用经纬度和地址
                val locationParam = "${location.longitude},${location.latitude}"
                _locationData.value = locationParam
                _currentCity.value = location.city
                onComplete(locationParam)
            },
            onFailure = { errorCode, errorInfo ->
                // 定位失败，使用默认位置
                _locationError.value = "定位失败: $errorInfo"
                _currentCity.value = defaultCity
                onComplete(defaultLocation)
            }
        )
    }

    // 获取默认位置
    fun getDefaultLocation(): String {
        return defaultLocation
    }

    fun getDefaultCity(): String {
        return defaultCity
    }
}